var addList = [];
var addTopicList = [];
var sendCustomers = [];
var sendTopics = [];
var success = [];
var rep = [];
//登录人员信息
var loginData = JSON.parse(decodeURIComponent(web.readCookie("loginData")));
var userID = loginData.user.user_ID;//获取用户的ID
var dataSource = new Array();
var dataSource1 = new Array();
var dataSource2 = new Array();
var oop=0

var table;   //table对象
dataSource1 = [];
dataSource2 = [];
var tokenVal = '';
var customerType = '';
var wareHouse = '';
var payType = '';
var custType = $("#custType").val();
var userid = custType;
console.log($("#custType").val());
var sendCouponType = $("#sendCouponType").val();
console.log("sendCouponType= " + sendCouponType);
var message = '';
var sendCondition = 0;

$("#twoOrThree").css({
    display: "block"
});
$("#two").css({
    display: "block"
});
$("#time").css({
    display: "block"
});
$("#topic-2").css({
    display: "block"
});
$("#kehu").css({
    display: "none"
})
//发券客户类型切换
function getCustType(e) {
    custType = $("#custType").val();
    addList = [];
    customerList(addList);
    console.log("custType=" + custType);
}

//发放条件切换
function changeSendCondition() {
    if ($("#sendCondition").val() == 1) {
        sendCondition = 1;
        $("#two-1").css({
            display: "none"
        });
        $("#two-2").css({
            display: "none"
        });

        $("#two-3").css({
            display: "none"
        });
        $('#orderAmount').val('');
        document.getElementById("wareHouse").checked = false;
        $("input[name='wareHouse']").prop("checked", false);
        $("input[name='payType']").prop("checked", false);
        //适用价格类型
        $("#pricetype").css({
            display: "none"
        });
    }
    if ($("#sendCondition").val() == 2) {
        sendCondition = 2;
        $("#two-1").css({
            display: "block"
        });
        $("#two-2").css({
            display: "block"
        });

        $("#two-3").css({
            display: "block"
        });
//适用价格类型
        $("#pricetype").css({
            display: "none"
        });

    }
    if ($("#sendCondition").val() == 3) {
        sendCondition = 3;
        $("#two-1").css({
            display: "none"
        });
        $("#two-2").css({
            display: "none"
        });

        $("#two-3").css({
            display: "none"
        });
        $('#orderAmount').val('');
        document.getElementById("wareHouse").checked = false;
        $("input[name='wareHouse']").prop("checked", false);
        $("input[name='payType']").prop("checked", false);
        //适用价格类型
        $("#pricetype").css({
            display: "none"
        });
    }
    if ($("#sendCondition").val() == 4) {
        sendCondition = 4;
        $("#two-1").css({
            display: "none"
        });
        $("#two-2").css({
            display: "none"
        });

        $("#two-3").css({
            display: "none"
        });
        $('#orderAmount').val('');
        document.getElementById("wareHouse").checked = false;
        $("input[name='wareHouse']").prop("checked", false);
        $("input[name='payType']").prop("checked", false);
        //适用价格类型
        $("input[name='priceType']").prop("checked", false);
        $("#pricetype").css({
            display: "inline"
        });
        $("#unlimited").css({
            display: "none"
        });
    }
}

//发券方式切换
function changeSendType() {
    if ($("#sendCouponType").val() == 1) {
        $("#twoOrThree").css({
            display: "none"
        });
        $("#customer").css({
            display: "block"
        });
        $("#topic-1").css({
            display: "block"
        });
        $("#topic-2").css({
            display: "none"
        });
        $("#two").css({
            display: "none"
        })
        $("#two-1").css({
            display: "none"
        });
        $("#two-2").css({
            display: "none"
        });

        $("#two-3").css({
            display: "none"
        });
        $("#time").css({
            display: "none"
        });
        $("#sendCondition").removeAttr("disabled");
        sendCouponType = 1;
        addList = [];
        addTopicList = [];
        customerType = '';
        $('#sendCondition').val(0);
        $('#orderAmount').val(0);
        $('#searchCoupon').val('');
        document.getElementById("customerType").checked = false;
        $("input[name='customerType']").prop("checked", false);
        document.getElementById("wareHouse").checked = false;
        $("input[name='wareHouse']").prop("checked", false);
        $("input[name='payType']").prop("checked", false);
        $("#logmin").val('');
        $("#logmax").val('');
        coupon_list_2(addTopicList);
        //适用价格类型
        $("input[name='priceType']").prop("checked", false);
        $("#pricetype").css({
            display: "none"
        });
    } else if ($("#sendCouponType").val() == 2) {
        $("#customer").css({
            display: "none"
        });
        $("#twoOrThree").css({
            display: "block"
        });
        $("#two").css({
            display: "block"
        })
        $("#time").css({
            display: "block"
        });
        $("#topic-1").css({
            display: "none"
        });
        $("#topic-2").css({
            display: "block"
        });
        $("#sendCondition").removeAttr("disabled");
        if ($('#sendCondition').val() == 1) {
            $("#two-1").css({
                display: "none"
            });
            $("#two-2").css({
                display: "none"
            });
            $("#two-3").css({
                display: "none"
            });
            $('#orderAmount').val(0);
            document.getElementById("wareHouse").checked = false;
            $("input[name='wareHouse']").prop("checked", false);
            $("input[name='payType']").prop("checked", false);
        } else if ($('#sendCondition').val() == 2) {
            $("#two-1").css({
                display: "block"
            });
            $("#two-2").css({
                display: "block"
            });

            $("#two-3").css({
                display: "block"
            });
        }
        $("#sendCondition").val('');
        sendCouponType = 2;
        addList = [];
        addTopicList = [];
        customerType = '';
        $('#custType').val('');
        $('#searchCoupon').val('');
        document.getElementById("customerType").checked = false;
        $("input[name='customerType']").prop("checked", false);
        $("#logmin").val('');
        $("#logmax").val('');
        customerList(addList);
        coupon_list(addTopicList);
        coupon_list_2(addTopicList);
        $("#customerTypef1").css({
            display: "inline"
        });
        $("#customerTypef2").css({
            display: "inline"
        });
        $("#customerTypef0").css({
            display: "inline"
        });

        $("#kehu").css({
            display: "none"
        })
        $("#customerTypes1").removeAttr("disabled")
        $("#customerTypes2").removeAttr("disabled")
        //适用价格类型
        $("input[name='priceType']").prop("checked", false);
        $("#pricetype").css({
            display: "none"
        });
    } else if ($("#sendCouponType").val() == 3) {
        $("#customer").css({
            display: "none"
        });
        $("#twoOrThree").css({
            display: "block"
        });
        $("#two").css({
            display: "none"
        })
        $("#two-1").css({
            display: "none"
        });
        $("#two-2").css({
            display: "none"
        });

        $("#two-3").css({
            display: "none"
        });
        $("#topic").show();
        $("#topic-1").css({
            display: "none"
        });
        $("#topic-2").show();
        $("#time").css({
            display: "block"
        });
        $("#sendCondition").removeAttr("disabled");
        sendCouponType = 3;
        addList = [];
        addTopicList = [];
        customerType = '';
        sendCondition = 0;
        $('#custType').val('');
        $('#searchCoupon').val('');
        $('#orderAmount').val(0);
        document.getElementById("customerType").checked = false;
        $("input[name='customerType']").prop("checked", false);
        document.getElementById("wareHouse").checked = false;
        $("input[name='wareHouse']").prop("checked", false);
        $("input[name='payType']").prop("checked", false);
        $("#logmin").val('');
        $("#logmax").val('');
        customerList(addList);
        coupon_list(addTopicList);
        coupon_list_2(addTopicList);
        $("#customerTypef1").css({
            display: "inline"
        });
        $("#customerTypef2").css({
            display: "inline"
        });
        $("#customerTypef0").css({
            display: "inline"
        });
        $("#kehu").css({
            display: "none"
        })
        $("#customerTypes1").removeAttr("disabled")
        $("#customerTypes2").removeAttr("disabled")
        //适用价格类型
        $("input[name='priceType']").prop("checked", false);
        $("#pricetype").css({
            display: "inline"
        });
        $("#unlimited").css({
            display: "inline"
        });
    }else if ($("#sendCouponType").val() == 4){

        sendCouponType = 4;
        sendCondition = 3;
        $("#customer").css({
            display: "none"
        });
        $("#twoOrThree").css({
            display: "block"
        });
        $("#two").css({
            display: "block"
        })
        $("#time").css({
            display: "block"
        });
        $("#topic-1").css({
            display: "none"
        });
        $("#topic-2").css({
            display: "block"
        });
        $('#orderAmount').val(0);
        $("#sendCondition").val('3');
        $("#sendCondition").attr("disabled","disabled");
        $("#customerTypef1").css({
            display: "none"
        });
        $("#customerTypef2").css({
            display: "none"
        });
        $("#customerTypef0").css({
            display: "none"
        });
        $("#kehu").css({
            display: "inline"
        })
        $('#searchCoupon').val('');
        addList = [];
        addTopicList = [];
        customerList("");
        coupon_list("");
        coupon_list_2("");
        $("#productList").html("")
        $("#customerTypes1").prop("checked", true);
        $("#customerTypes1").attr("disabled","disabled")
        $("#customerTypes2").prop("checked", true);
        $("#customerTypes2").attr("disabled","disabled")
        //适用价格类型
        $("input[name='priceType']").prop("checked", false);
        $("#pricetype").css({
            display: "none"
        });
    }
    console.log("sendCouponType= " + sendCondition);
}

var count = 0;//默认 没有
//子级选中
$("input[name='customerType']").change(function () {
    customerType = '';
    var groupCheckbox = $("input[name='customerType']");
    var groupCheckboxch=$("input[name='customerType']:checked")
    for (var i = 0; i < groupCheckbox.length; i++) {
        if (groupCheckbox[i].checked) {
            var val = groupCheckbox[i].value;
            if (i == groupCheckbox.length - 1) {
                customerType += val;
            } else {
                customerType += val + ',';
            }
        }
        //全选按钮选中
        if(groupCheckboxch.length==groupCheckbox.length){
            document.getElementById("customerType").checked = true;
        }else {
            document.getElementById("customerType").checked = false;
        }
    }
});
//全选
function check() {
    if (count == 0) {
        document.getElementById("customerType").checked = true;
        $("input[name='customerType']").prop("checked", true);
        count = 1;
        customerType = document.getElementById("customerType").value;
        console.log(customerType);
    } else if (count == 1) {
        document.getElementById("customerType").checked = false;
        $("input[name='customerType']").prop("checked", false);
        count = 0;
        customerType = '';
    }
}

$("input[name='wareHouse']").change(function () {
    wareHouse = '';
    var groupCheckbox = $("input[name='wareHouse']");
    for (i = 0; i < groupCheckbox.length; i++) {
        if (groupCheckbox[i].checked) {
            var val = groupCheckbox[i].value;
            if (i == groupCheckbox.length - 1) {
                wareHouse += val;
            } else {
                wareHouse += val + ',';
            }
        }
        if (groupCheckbox[i].checked == false) {
            document.getElementById("wareHouse").checked = false;
        }
    }
    console.log(wareHouse);

});

function warehouseCheck() {
    if (count == 0) {
        document.getElementById("wareHouse").checked = true;
        $("input[name='wareHouse']").prop("checked", true);
        count = 1;
        wareHouse = document.getElementById("wareHouse").value;
        console.log(wareHouse);
    } else if (count == 1) {
        document.getElementById("wareHouse").checked = false;
        $("input[name='wareHouse']").prop("checked", false);
        count = 0;
        wareHouse = '';
    }
}

$("input[name='payType']").change(function () {
    var groupCheckbox = $("input[name='payType']");
    for (i = 0; i < groupCheckbox.length; i++) {
        if (groupCheckbox[i].checked) {
            var val = groupCheckbox[i].value;
            payType += val + ',';
        }
    }
    console.log(payType);
    payType = '';
});

if ($("#sendCouponType") != 1) {
    var startTime = $("#logmin").val();
    var endTime = $("#logmax").val();
}

function putDataToPage() {
    console.log(1111);
    /*渲染spu sku值到页面*/
    var formData = new FormData();
    formData.append("userId", userID);
    formData.append("custType", custType);
    formData.append("token", tokenVal);
    formData.append('file', $("#fileUp")[0].files[0]);
    $.ajax({
        url: root.couponInter.coupon_excelImportUser,
        cache: false,  //禁用缓存
        type: "POST",
        // 告诉jQuery不要去处理发送的数据
        processData: false,
        // 告诉jQuery不要去设置Content-Type请求头
        contentType: false,
        data: formData,
        success: function (data) {
            console.log(data);
            $('#fileUp').val('');
            if (data.code == 1) {
                if (data.message === '提示:导入的客户不存在!') {
                    if (data.failList != null && data.failList.length > 0) {
                        var hang = '';
                        for (var i = 0; i < data.failList.length; i++) {
                            if (i == data.failList.length - 1) {
                                hang += data.failList[i];
                            } else {
                                hang += data.failList[i] + ",";
                            }
                        }
                        $.Huimodalalert('第 {' + hang + '} 行的客户不存在！请您检查数据再导入!', 5000);
                    }
                } else {
                    $.Huimodalalert(data.message, 5000);
                    return;
                }
            } else {
                if (data.sumNum == 0) {
                    $.Huimodalalert('导入的客户表中没有数据,请添加数据!', 5000);
                    return;
                } else {
                    console.log('aaaaaaaaaaa');
                    console.log(addList);
                    if (data.successList != null && data.successList.length != 0) {
                        tokenVal = data.successList[0].sendCustomerToken;
                    }
                    for (var i = 0; i < data.successList.length; i++) {
                        success.push(data.successList[i]);
                    }
                    console.log(success);
                    if (addList.length > 0) {
                        console.log('bbbbbbbbbbbbbb');
                        for (var i = 0; i < addList.length; i++) {
                            success.push(addList[i]);
                        }
                        addList = [];
                        // var arr = [];
                        // for(let val of success){
                        //     arr.push(val.custId)
                        // }
                        // var newArr = [];
                        // var newArr2 = [];
                        // for(var i =0;i<arr.length-1;i++){
                        //     if(newArr.indexOf(arr[i]) == -1){
                        //         newArr.push(arr[i]);
                        //         newArr2.push(success[i]);
                        //     }
                        // }
                        // success = newArr2;

                        var obj = {};
                        success = success.reduce(function (item, next) {
                            obj[next.memberId] ? '' : obj[next.memberId] = true && item.push(next);
                            return item;
                        }, []);
                        console.log(success);
                        for (var i = 0; i < success.length; i++) {
                            addList.push(success[i]);
                        }
                        addList = addList.distinct();
                        customerList(addList);
                    } else {
                        addList = [];
                        console.log('cccccccccccccccc');
                        for (var i = 0; i < success.length; i++) {
                            addList.push(success[i]);
                        }
                        var obj = {};
                        addList = addList.reduce(function (item, next) {
                            obj[next.memberId] ? '' : obj[next.memberId] = true && item.push(next);
                            return item;
                        }, []);
                        console.log(addList);
                        addList = addList.distinct();
                        customerList(addList);
                    }

                    var hanghao = '';
                    for (var i = 0; i < data.failList.length; i++) {
                        if (i == data.failList.length - 1) {
                            hanghao += data.failList[i];
                        } else {
                            hanghao += data.failList[i] + ",";
                        }
                    }
                    var z = data.sumNum;
                    var q = data.successList.length;
                    var e = data.failList.length;
                    var i = q + e;
                    if (data.message === '重复数据已覆盖') {
                        $.Huimodalalert('共导入' + z + '条客户信息！成功导入{' + q + '}个客户！第 {' + hanghao + '} 行的客户不存在！有重复数据已覆盖!', 5000);
                    } else if (e == 0) {
                        if (success.length != data.successList.length) {
                            $.Huimodalalert('共导入' + addList.length + '条客户信息！重复数据已覆盖,全部导入成功！', 3000);
                        } else {
                            $.Huimodalalert('共导入' + success.length + '条客户信息！全部导入成功！', 3000);
                        }
                    } else if (q != 0 && e != 0) {
                        console.log("33333")
                        $.Huimodalalert('共导入' + z + '条客户信息！成功导入{' + q + '}个客户,未导入{' + e + '}个客户！第 {' + hanghao + '} 行的客户不存在！', 5000);
                    } else if (q == 0 && e != 0) {
                        $.Huimodalalert('共导入' + z + '条客户信息！未导入{' + e + '}个客户！第 {' + hanghao + '} 行的客户不存在！', 5000);
                    }
                }
            }
        }
    });
}

function downloadTem() {
    $.ajax({
        url: "http://192.168.7.100:8087/downloadProductExcelTemplate",
        cache: false,  //禁用缓存
        type: "GET",
        data: "",
        success: function (data) {
        }
    });
}

function upLoadFile() {

    $("#fileUp").trigger('click');
}

$(document).click(function (e) {
    var target = $(e.target);
    if (target[0].id != 'searchCust') {
        $('.customers').remove();
        $('.custlist').addClass('hide');
    }
    if (target[0].id != 'searchCoupon') {
        $('.coupons').remove();
        $('.couponlist').addClass('hide');
    }

})

var flag = true;
$('#searchCust').on('compositionstart', function () {
    flag = false;
})
$('#searchCust').on('compositionend', function () {
    flag = true;
})
var arr = new Array();
//焦点查询
$("#searchCust").focus('input', function () {

    var _this = this;
    setTimeout(function () {
        if (flag) {
            var value = $(_this).val();
            if (value == '') {
                return;
            }
            $('li').remove();
            $.ajax({
                url: root.couponInter.coupon_queryCustomerByCustomerName,
                cache: false,  //禁用缓存
                type: "POST",
                dataType: 'json',
                data: {
                    "customerName": value,
                    "custType": custType
                },
                success: function (data) {
                    if (data.code == 0) {
                        if (value != '') {
                            $('.customers').remove();
                            document.getElementsByClassName('custlist')[0].classList.remove('hide');
                            for (var i = 0; i < data.customerInfos.length; i++) {
                                $("#custList").append('<li id="' + data.customerInfos[i].customerId + '" class="customers">' + data.customerInfos[i].customerName + '</li>');
                            }
                        }
                        else {
                            document.getElementsByClassName('custlist')[0].classList.add('hide');
                        }
                        $('.customers').one('click', function () {
                            $('#searchCust').val('');
                            // $('.customers').remove();
                            userid = custType;
                            $.ajax({
                                url: root.couponInter.coupon_saveCouponSendCustomer,
                                cache: false,  //禁用缓存
                                type: "post",
                                dataType: 'json',
                                data: {
                                    'custId': this.id,
                                    'userId': userID,
                                    'custType': custType,
                                    'token': tokenVal
                                },
                                success: function (data) {
                                    console.log(data);
                                    var falg = 0;
                                    console.log(addList);
                                    var custData = data.data;
                                    console.log(custData);
                                    if (custType != custData[0].custType) {
                                        $.Huimodalalert('添加的客户类型与选择的客户类型不一致,请重新选择!', 2000);
                                        return;
                                    }
                                    for (var i = 0; i < addList.length; i++) {
                                        if (data.data[0].customerId == addList[i].customerId) {
                                            falg = 1;
                                        }
                                    }
                                    if (falg == 1) {
                                        $.Huimodalalert('已存在,请重新添加!', 2000);
                                        falg = 0;
                                        return;
                                    } else {
                                        addList.push(custData[0]);
                                    }
                                    tokenVal = data.data[0].sendCustomerToken;
                                    customerList(addList);
                                }
                            });
                        })
                    } else {
                        $.Huimodalalert(data.message, 2000);
                        return;
                    }

                }
            });
        }
    }, 0)
});
//输入查询
$('#searchCust').on('input', function () {
    var _this = this;
    setTimeout(function () {
        if (flag) {
            var value = $(_this).val();
            if (value == '') {
                return;
            }
            $('li').remove();
            $.ajax({
                url: root.couponInter.coupon_queryCustomerByCustomerName,
                cache: false,  //禁用缓存
                type: "POST",
                dataType: 'json',
                data: {
                    "customerName": value,
                    "custType": custType
                },
                success: function (data) {
                    console.log(data);
                    if (data.code == 0) {
                        if (value != '') {
                            $('.customers').remove();
                            document.getElementsByClassName('custlist')[0].classList.remove('hide');
                            for (var i = 0; i < data.customerInfos.length; i++) {
                                $("#custList").append('<li id="' + data.customerInfos[i].customerId + '" class="customers">' + data.customerInfos[i].customerName + '</li>');
                            }
                        }
                        else {
                            document.getElementsByClassName('custlist')[0].classList.add('hide');
                        }
                        $('.customers').on('click', function () {
                            $('#searchCust').val('');
                            // alert(this.id)
                            console.log(this.id.length)
                            // $('.customers').remove();
                            userid = custType;
                            $.ajax({
                                url: root.couponInter.coupon_saveCouponSendCustomer,
                                cache: false,  //禁用缓存
                                type: "post",
                                dataType: 'json',
                                data: {
                                    'custId': this.id,
                                    'userId': userID,
                                    'custType': custType,
                                    'token': tokenVal
                                },
                                success: function (data) {
                                    console.log(data);
                                    var falg = 0;
                                    console.log(addList);
                                    var custData = data.data;
                                    console.log(custData);
                                    if (custType != custData[0].custType) {
                                        $.Huimodalalert('添加的客户类型与选择的客户类型不一致,请重新选择!', 2000);
                                        return;
                                    }
                                    for (var i = 0; i < addList.length; i++) {
                                        if (data.data[0].customerId == addList[i].customerId) {
                                            falg = 1;
                                        }
                                    }
                                    if (falg == 1) {
                                        $.Huimodalalert('已存在,请重新添加!', 2000);
                                        falg = 0;
                                        return;
                                    } else {
                                        addList.push(custData[0]);
                                    }
                                    tokenVal = data.data[0].sendCustomerToken;
                                    customerList(addList);
                                }
                            });
                        })
                    } else {
                        $.Huimodalalert(data.message, 2000);
                        return;
                    }

                }
            });
        }
    }, 0)
});

//客户数据渲染
function customerList(data, index) {
    // sessionStorage.setItem("authorizedUsers", JSON.stringify(data));
    dataSource.splice(0, dataSource.length);//清空数组
    console.log(data)
    $.each(data, function (i, field) {
        var rowData = new Array();
        rowData.push(field.memberId);
        rowData.push(field.custType);
        rowData.push(field.custName);
        rowData.push(field.custArea);
        dataSource.push(rowData);
    });
    console.log(dataSource);
    initDataTable(dataSource);

    function initDataTable(dataSource) {

        var dttable = $('#datatable').dataTable(); // 初始化dataTable，清空上一个值
        dttable.fnClearTable(); //清空一下table
        dttable.fnDestroy(); //还原初始化了的datatable

        $("#datatable").DataTable({
            "bSort": false,//禁止排序
            "autoWidth": false,
            "ordering": true,
            "searching": false,
            "paging": true,
            "retrieve": true,
            "destroy": true,
            "bAutoWidth": false,
            "bLengthChange": false,
            "aLengthMenu": [10, 25, 50],
            "oLanguage": {
                "sLengthMenu": "每页显示 _MENU_ 条记录",
                "sZeroRecords": "抱歉， 没有找到",
                "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
                "sInfoEmpty": "没有数据",
                "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "前一页",
                    "sNext": "后一页",
                    "sLast": "尾页"
                },
                "sZeroRecords": "没有检索到数据"
            },
            data: dataSource,
            columnDefs: [
                // {"data":null, "targets":0 },
                {
                    "visible": true,
                    "targets": 0
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = '';
                        if (row[1] == 20) {
                            val = '普通客户';
                            return val;
                        }
                        else if (row[1] == 30) {
                            val = '认证客户';
                            return val;
                        }
                        else if (row[1] == 12) {
                            val = '签约客户(分销)';
                            return val;
                        }
                        else if (row[1] == 11) {
                            val = '签约客户(非分销)';
                            return val;
                        }
                    },
                    "targets": 1
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = '<a><span class="list" onclick="customerDelete(this)" id="' + row[0] + '">删除</span></a>';
                        return val;
                    },
                    "targets": 4
                }
            ]
        });
    };
}

//客户数据删除
function customerDelete(e) {
    console.log("删除客户");
    addList = addList.distinct();
    console.log(addList);
    layer.confirm('您确定要删除该条数据吗？', function (index) {
        for (var i = 0; i < addList.length; i++) {
            if (addList[i].customerId == e.id) {
                addList.splice(i, 1);
                break;
            }
        }
        customerList(addList);
        $.Huimodalalert('删除成功！', 1000);
        layer.close(index);
    });

}

var flag1 = true;
var topicNum = 0;
var couponProducts = [];
var errorMessage = '';
$('#searchCoupon').on('compositionstart', function () {
    flag1 = false;
})
$('#searchCoupon').on('compositionend', function () {
    flag1 = true;
})
//焦点查询
$('#searchCoupon').focus('input', function () {
    var _this = this;
    setTimeout(function () {
        if (flag1) {
            var value = $(_this).val();
            if (value == '') {
                return;
            }
            $('li').remove();
            $.ajax({
                url: root.couponInter.coupon_getCouponTopic,
                cache: false,  //禁用缓存
                type: "POST",
                dataType: 'json',
                data: {
                    "sendCouponType":$('#sendCouponType').val(),
                    "topicNameOrCode": value
                },
                success: function (data) {
                    console.log(data)
                    if (value != '') {
                        $('.coupons').remove();
                        document.getElementsByClassName('couponlist')[0].classList.remove('hide');
                        for (var i = 0; i < data.couponTopicList.length; i++) {
                            $("#couponList").append('<li id="' + data.couponTopicList[i].topicId + '" class="coupons">' + data.couponTopicList[i].topicName + '</li>');
                        }
                    }
                    else {
                        document.getElementsByClassName('couponlist')[0].classList.add('hide');
                    }
                    $('.coupons').on('click', function () {
                        console.log(tokenVal)
                        $('#searchCoupon').val(this.innerHTML);
                        $('.coupons').remove();
                        userid = custType;
                        $.ajax({
                            url: root.couponInter.coupon_saveCouponSendTopic,
                            cache: false,  //禁用缓存
                            type: "post",
                            dataType: 'json',
                            data: {
                                'topicId': this.id,
                                'userId': userID,
                                'token': tokenVal,
                                'sendCouponType': sendCouponType
                            },
                            success: function (data) {
                                console.log(data)
                                if (data.errorCode == 0) {
                                    for (var i = 0; i < addTopicList.length; i++) {
                                        console.log(addTopicList[i][0]);
                                        if (data.data[0].topicId == addTopicList[i][0].topicId) {
                                            $.Huimodalalert('已存在,请重新添加!', 2000);
                                            return;
                                        } else {
                                            continue;
                                        }
                                    }
                                    if (tokenVal == '') {
                                        tokenVal = data.data[0].sendTopicToken;
                                    }
                                    if($("#sendCouponType").val() == 4){
                                        if(oop==0){
                                            if($('#productList tr').length==0) {
                                                addTopicList.push(data.data);
                                            }
                                        }else {
                                            addTopicList.push(data.data);
                                        }
                                    }else {
                                        addTopicList.push(data.data);
                                    }

                                    if (sendCouponType != 1) {
                                        //当为抽奖发送时列表只能填入一条数据
                                        console.log($('#productList tr').length)
                                        if($("#sendCouponType").val() == 4){
                                            if(oop==0){
                                                console.log($('#productList tr').length)
                                                if($('#productList tr').length==0) {
                                                    coupon_list_2(addTopicList);
                                                }
                                            }else {
                                                coupon_list_2(addTopicList);
                                            }

                                        }else {
                                            coupon_list_2(addTopicList);
                                        }
                                    } else {
                                        coupon_list(addTopicList);
                                    }
                                }
                                if (data.errorCode == 1) {
                                    $.Huimodalalert(data.msg, 2000);
                                }
                            }
                        });
                    })
                }
            });
        }
    }, 0)
})
//输入查询
$('#searchCoupon').on('input', function () {
    var _this = this;
    setTimeout(function () {
        if (flag1) {
            var value = $(_this).val();
            if (value == '') {
                return;
            }
            $('li').remove();
            $.ajax({
                url: root.couponInter.coupon_getCouponTopic,
                cache: false,  //禁用缓存
                type: "POST",
                dataType: 'json',
                data: {
                    "sendCouponType":$('#sendCouponType').val(),
                    "topicNameOrCode": value
                },
                success: function (data) {
                    if (value != '') {
                        $('.coupons').remove();
                        document.getElementsByClassName('couponlist')[0].classList.remove('hide');
                        for (var i = 0; i < data.couponTopicList.length; i++) {
                            $("#couponList").append('<li id="' + data.couponTopicList[i].topicId + '" class="coupons">' + data.couponTopicList[i].topicName + '</li>');
                        }
                    }
                    else {
                        document.getElementsByClassName('couponlist')[0].classList.add('hide');
                    }
                    $('.coupons').on('click', function () {
                        console.log(tokenVal)
                        $('#searchCoupon').val(this.innerHTML);
                        $('.coupons').remove();
                        userid = custType;
                        $.ajax({
                            url: root.couponInter.coupon_saveCouponSendTopic,
                            cache: false,  //禁用缓存
                            type: "post",
                            dataType: 'json',
                            data: {
                                'topicId': this.id,
                                'userId': userID,
                                'token': tokenVal,
                                'sendCouponType': sendCouponType
                            },
                            success: function (data) {
                                console.log(data);
                                console.log(addTopicList);
                                if (data.errorCode == 0) {
                                    for (var i = 0; i < addTopicList.length; i++) {
                                        console.log(addTopicList[i][0].topicId);
                                        if (data.data[0].topicId == addTopicList[i][0].topicId) {
                                            $.Huimodalalert('已存在,请重新添加!', 2000);
                                            return;
                                        } else {
                                            continue;
                                        }
                                    }
                                    if (tokenVal == '') {
                                        tokenVal = data.data[0].sendTopicToken;
                                    }

                                    if($("#sendCouponType").val() == 4){
                                        if(oop==0){
                                            if($('#productList tr').length==0) {
                                                addTopicList.push(data.data);
                                            }
                                        }else {
                                            addTopicList.push(data.data);
                                        }
                                    }else {
                                        addTopicList.push(data.data);
                                    }

                                    if (sendCouponType != 1) {
                                        //当为抽奖发送时列表只能填入一条数据
                                        if($("#sendCouponType").val() == 4){
                                            console.log($('#productList tr').length)
                                            if(oop==0){
                                                if($('#productList tr').length==0) {
                                                    coupon_list_2(addTopicList);
                                                }
                                            }else {
                                                coupon_list_2(addTopicList);
                                            }

                                        }else {
                                            coupon_list_2(addTopicList);
                                        }

                                    } else {
                                        coupon_list(addTopicList);
                                    }
                                }
                                if (data.errorCode == 1) {
                                    $.Huimodalalert(data.msg, 2000);
                                }
                            }
                        });
                    })
                }
            });
        }
    }, 0)
})
var coupon_list = function (data) {
    console.log(data);
    dataSource2.splice(0, dataSource2.length);//清空数组
    $.each(data, function (k, v) {
        $.each(v, function (i, field) {
            var rowData = new Array();
            /* var statu=''
             if(data.couponSendTopics.topicStatus)*/
            rowData.push(field.topicCode);
            rowData.push(field.topicName);
            rowData.push(field.amount);
            rowData.push(field.useBegtime);
            rowData.push(field.topicStatus); //10已生效，20已失效
            rowData.push(field.issuedNum);
            rowData.push(field.sendNum);
            rowData.push(field.useEndtime);
            rowData.push(field.topicId);
            rowData.push(field.sendTopicId);
            rowData.push(field.dayNumber);
            rowData.push(field.topicType);
            dataSource2.push(rowData);
        });
    });
    initDataTable(dataSource2);

    function initDataTable(dataSource2) {
        var dttable = $('#datatable1').dataTable(); // 初始化dataTable，清空上一个值
        dttable.fnClearTable(); //清空一下table
        dttable.fnDestroy(); //还原初始化了的datatable
        $("#datatable1").DataTable({
            "autoWidth": true,
            "ordering": true,
            "searching": false,
            "paging": true,
            "retrieve": true,
            "destroy": true,
            "bAutoWidth": false,
            "bLengthChange": false,
            "aLengthMenu": [10, 25, 50],
            "oLanguage": {
                "sLengthMenu": "每页显示 _MENU_ 条记录",
                "sZeroRecords": "抱歉， 没有找到",
                "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
                "sInfoEmpty": "没有数据",
                "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "前一页",
                    "sNext": "后一页",
                    "sLast": "尾页"
                },
                "sZeroRecords": "没有检索到数据"
            },
            data: dataSource2,
            columnDefs: [
                {
                    "visible": true,
                    "targets": 0
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = '';
                        if (row[11] == 10) {
                            val = '满减券';
                        } else {
                            val = '运费券';
                        }
                        return val;
                    },
                    "targets": 0
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[0]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 1
                }, {
                    "render": function (data, type, row, meta) {
                        var val = row[1]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 2
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[2]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 3
                },
                {
                    "render": function (data, type, row, meta) {
                        if (row[10] == 0) {
                            var val = '<span>' + row[3] + '</span><br>~<br><span>' + row[7] + '</span>';
                            return val;
                        }
                        else {
                            var val = '<span>领到券当日开始' + row[10] + '天内有效</span>';
                            return val;
                        }
                    },
                    "targets": 4
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = '<input class="sendNum"  data-id="' + row[5] + '" type="text" name="' + row[9] + '" id="' + row[8] + '"  onafterpaste="this.value=this.value.replace(/\\D/g,\'\')" value="' + row[6] + '" style="width:50px;text-align: center;border: 1px solid #333" onkeyup="changeNum(this);this.value=this.value.replace(/\\D/g,\'\');">';
                        return val;
                    },
                    "targets": 6
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = '<a><span class="list" onclick="topicDelete(this)" id="' + row[8] + '">删除</span></a>';
                        return val;
                    },

                    "targets": 7
                }
            ]
        });
    };
};

var coupon_list_2 = function (data) {
    dataSource2.splice(0, dataSource2.length);//清空数组
    $.each(data, function (k, v) {
        console.log(data);
        $.each(v, function (i, field) {
            console.log(v);
            var rowData = new Array();
            /* var statu=''
             if(data.couponSendTopics.topicStatus)*/
            rowData.push(field.topicCode);
            rowData.push(field.topicName);
            rowData.push(field.amount);
            rowData.push(field.useBegtime);
            rowData.push(field.topicStatus); //10已生效，20已失效
            rowData.push(field.issuedNum);
            rowData.push(field.sendNum);
            rowData.push(field.useEndtime);
            rowData.push(field.topicId);
            rowData.push(field.sendTopicId);
            rowData.push(field.dayNumber);
            rowData.push(field.sendTotalNum);
            rowData.push(field.topicType);
            dataSource2.push(rowData);
        });
    });
    initDataTable(dataSource2);

    function initDataTable(dataSource2) {
        var dttable = $('#datatable2').dataTable(); // 初始化dataTable，清空上一个值
        dttable.fnClearTable(); //清空一下table
        dttable.fnDestroy(); //还原初始化了的datatable
        $("#datatable2").DataTable({
            "autoWidth": true,
            "ordering": true,
            "searching": false,
            "paging": true,
            "retrieve": true,
            "destroy": true,
            "bAutoWidth": false,
            "bLengthChange": false,
            "aLengthMenu": [10, 25, 50],
            "oLanguage": {
                "sLengthMenu": "每页显示 _MENU_ 条记录",
                "sZeroRecords": "抱歉， 没有找到",
                "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
                "sInfoEmpty": "没有数据",
                "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "前一页",
                    "sNext": "后一页",
                    "sLast": "尾页"
                },
                "sZeroRecords": "没有检索到数据"
            },
            data: dataSource2,
            columnDefs: [
                {
                    "visible": true,
                    "targets": 0
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = '';
                        if (row[12] == 10) {
                            val = '满减券';
                        } else {
                            val = '运费券';
                        }
                        return val;
                    },
                    "targets": 0
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[0]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 1
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[1]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 2
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[2]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 3
                },
                {
                    "render": function (data, type, row, meta) {
                        if (row[10] == 0) {
                            var val = '<span>' + row[3] + '</span><br>~<br><span>' + row[7] + '</span>';
                            return val;
                        }
                        else {
                            var val = '<span>领到券当日开始' + row[10] + '天内有效</span>';
                            return val;
                        }
                    },
                    "targets": 4
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[5];
                        return val;
                    },
                    "targets": 5
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = 1;
                        return val;
                    },
                    "targets": 6
                },
                {
                    "render": function (data, type, row, meta) {
                        if (row[11] == 0) {
                            row[11] = '';
                        }
                        var val = '<input class="sendNum" type="text" name="' + row[11] + '" id="' + row[8] + '" value="' + row[11] + '"  onafterpaste="this.value=this.value.replace(/\\D/g,\'\')"  style="width:50px;text-align: center;border: 1px solid #333" onkeyup="changeTotalNum(this);this.value=this.value.replace(/\\D/g,\'\');">';
                        return val;
                    },
                    "targets": 7
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = '<a><span class="list" onclick="topicDelete2(this)" id="' + row[8] + '">删除</span></a>';
                        return val;
                    },

                    "targets": 8
                }
            ]
        });
    };
};

function topicDelete(e) {
    console.log(1111);
    addTopicList = addTopicList.distinct();
    console.log(addTopicList);
    layer.confirm('您确定要删除该条数据吗？', function (index) {
        for (var i = 0; i < addTopicList.length; i++) {
            if (addTopicList[i][0].topicId == e.id) {
                addTopicList.splice(i, 1);
                break;
            }
        }
        console.log(addTopicList);
        coupon_list(addTopicList);
        $.Huimodalalert('删除成功！', 1000);
        layer.close(index);
    });
}

function topicDelete2(e) {
    // console.log(2222);
    addTopicList = addTopicList.distinct();
    // console.log(addTopicList);
    layer.confirm('您确定要删除该条数据吗？', function (index) {
        for (var i = 0; i < addTopicList.length; i++) {
            if (addTopicList[i][0].topicId == e.id) {
                addTopicList.splice(i, 1);
                break;
            }
        }
        // console.log(addTopicList);
        coupon_list_2(addTopicList);
        oop=0
        $.Huimodalalert('删除成功！', 1000);
        if($("#sendCouponType").val() == 4){
            $("#productList").html("")
        }
        layer.close(index);
    });

}

function changeNum(e) {
    console.log('qqqqqq');
    console.log(e);
    // if (e.value == '') {
    //     $.Huimodalalert('不可为空!', 2000);
    //     return;
    // }
    if (!(/^[0-9]+$/.test(e.value))) {
        $.Huimodalalert('请输入数字!', 2000);
        return;
    }
    console.log(addList.length);
    console.log(e.value);

    // console.log($(e).attr('data-id'));
    // console.log($(e).parent().prev().text())
    // console.log($('#issuedNum').val());
    // var topicid=e.parentNode.previousSibling.previousSibling.firstChild.id;
    // console.log(topicid)
    var issuedNum = $(e).attr('data-id');
    var willSendNum = addList.length * e.value;
    if (willSendNum > issuedNum) {
        $.Huimodalalert('发放总计: ' + willSendNum + ' 张,该主题剩余: ' + issuedNum + ' 张,剩余数量不足,请重新输入!', 2000);
        for (var i = 0; i < addTopicList.length; i++) {
            if (addTopicList[i][0].topicId == e.id) {
                addTopicList[i][0].sendNum = e.value;
            }
        }
        return;
    } else {
        for (var i = 0; i < addTopicList.length; i++) {
            if (addTopicList[i][0].topicId == e.id) {
                addTopicList[i][0].sendNum = e.value;
            }
        }

    }
}

function changeTotalNum(e) {
    console.log(e);
    if (e.value == '') {
        $.Huimodalalert('不可为空!', 2000);
        return;
    }
    if (!(/^[0-9]+$/.test(e.value))) {
        $.Huimodalalert('请输入数字!', 2000);
        return;
    }
    sendTotalNum = e.value;
    // console.log("sendTotalNum= " + sendTotalNum);
    if (sendTotalNum == 0) {
        $.Huimodalalert('总发放数量不能为0', 2000);
        return;
    }
    $.ajax({
        url: root.couponInter.coupon_updateIssuedNumAndsendSum,
        cache: false,  //禁用缓存
        type: "POST",
        dataType: 'json',
        data: {
            "sendNum": sendTotalNum,
            // "topicId":topicid,
            // "sendTopicId": e.id.split('a')[0],
            "topicId": e.id,
            "sendCouponType": sendCouponType,
            "token": tokenVal
        },
        success: function (data) {
            // console.log(data);
            if (data.code == 0) {
                // $.Huimodalalert(data.message,2000);
                console.log(addTopicList);
                for (var i = 0; i < addTopicList.length; i++) {
                    console.log(addTopicList[i][0]);
                    if (addTopicList[i][0].topicId == e.id) {
                        addTopicList[i][0].sendTotalNum = sendTotalNum;
                        console.log("sendTotalNum " + addTopicList[i][0].sendTotalNum);
                    }

                    if (i == addTopicList.length - 1) {
                        console.log('结束');
                        console.log(addTopicList);
                    }
                }
                addTopicList = addTopicList.distinct();
            }
            else {
                $.Huimodalalert(data.message, 2000);
                e.value = 1;
            }
        },
        error: function () {
            $.Huimodalalert('异常不可键入！', 2000);
        }
    });
}

$("#form-member-add").validate({
    rules: {
        sendCouponName: {
            required: true,
        },
        /* searchCoupon: {
             required: true,
         },
         searchCust: {
             required: true,
         },*/
        sendReasonDutyDept: {
            required: true,
        },
        sendCouponReason: {
            required: true,
        },
        couponNum: {
            min: 1,
        },


    },
    messages: {
        sendCouponReason: {
            required: ""
        },
        sendReasonDutyDept: {
            required: ""
        },
    },
    onkeyup: false,
    focusCleanup: true,
    success: 'valid',

    submitHandler: function () {
        console.log("submit");
        console.log("customerType " + customerType);
        console.log("wareHouse" + wareHouse);
        if (customerType == '') {
            if ($('#sendCouponType').val() == 2 || $('#sendCouponType').val() == 3) {
                if (document.getElementById("customerType").checked) {
                    customerType = $('#customerType').val();
                } else {
                    var groupCheckbox = $("input[name='customerType']");
                    for (i = 0; i < groupCheckbox.length; i++) {
                        if (groupCheckbox[i].checked) {
                            var val = groupCheckbox[i].value;
                            if (i == groupCheckbox.length - 1) {
                                customerType += val;
                            } else {
                                customerType += val + ',';
                            }
                        }
                    }

                }
                console.log("customerType " + customerType);
            }
        }
        if ($('#sendCondition').val() == 2) {
            if (wareHouse == '') {
                if (document.getElementById("wareHouse").checked) {
                    wareHouse = $('#wareHouse').val();
                } else {
                    var groupCheckbox = $("input[name='wareHouse']");
                    for (i = 0; i < groupCheckbox.length; i++) {
                        if (groupCheckbox[i].checked) {
                            var val = groupCheckbox[i].value;
                            if (i == groupCheckbox.length - 1) {
                                wareHouse += val;
                            } else {
                                wareHouse += val + ',';
                            }
                        }
                    }
                }
                console.log("wareHouse" + wareHouse);
            }
            if (payType == '') {
                var groupCheckbox = $("input[name='payType']");
                for (i = 0; i < groupCheckbox.length; i++) {
                    if (groupCheckbox[i].checked) {
                        var val = groupCheckbox[i].value;
                        if (i == groupCheckbox.length - 1) {
                            payType += val;
                        } else {
                            payType += val + ',';
                        }
                    }
                }
                console.log("payType" + payType);
            }
        }
        console.log($(".sendNum").length);
        var a = $(".sendNum");
        console.log(a);
        for (var i = 0; i < a.length; i++) {
            console.log(a[i]);
            if ($(a[i]).val() == "") {
                console.log('wwww');
                if (sendCouponType != 1) {
                    $.Huimodalalert('总发放数量不能为空！', 2000);
                    return;
                } else {
                    $.Huimodalalert('发放数量不能为空！', 2000);
                    return;
                }
            }
        }
        // alert("12-提交事件!");
        // if (addList.length > 0) {
        //     for (var i = 0; i < addList.length; i++) {
        //         console.log(addList[i]);
        //         if (addList[i].length == 1) {
        //             sendCustomers.push(addList[i][0]);
        //         } else if (addList[i].length > 1) {
        //             for (var j = 0; j < addList[i].length; j++) {
        //                 console.log(addList[i][j]);
        //                 sendCustomers.push(addList[i][j]);
        //             }
        //         }
        //     }
        // }
        if (addTopicList.length > 0) {
            for (var i = 0; i < addTopicList.length; i++) {
                if (sendCouponType != 1 && addTopicList[i][0].sendTotalNum == 0) {
                    $.Huimodalalert('总发放数量不能为0或空！', 2000);
                    return;
                }
                // console.log("1111111 "+JSON.stringify(addTopicList[i]));
                sendTopics.push(addTopicList[i][0]);

            }
        }

            if(sendCouponType==2){
                if(sendCondition==4){
                    if($("input[name=priceType]:checked").val()==undefined){
                        $.Huimodalalert('请选择适用价格类型！', 2000);
                        return;
                    }
                }
            }else  if(sendCouponType==3){
                if($("input[name=priceType]:checked").val()==undefined){
                    $.Huimodalalert('请选择适用价格类型！', 2000);
                    return;
                }
            }

        sendTopics = sendTopics.distinct();
        if (sendCouponType != 1 && $('#logmin').val() == '') {
            $.Huimodalalert('生效日期不能为空！', 2000);
            return;
        }
        // console.log("提交");
        // console.log("sendCouponType" + sendCouponType);
        // console.log(customerType);
        console.log(sendCustomers.length);
        console.log('sendTopics ' + JSON.stringify(sendTopics));
        // console.log($('#orderAmount').val());

        // 加载等待样式
        $("#beijing").css("display", "block");
        $("#myLoading").css("display", "block");
        $("#bottm").attr("disabled", true);
        var customerTypess=""
        if($("#sendCouponType").val() == 4){
            customerTypess="20,30,"
        }else {
            customerTypess= customerType
        }

        $.ajax({
            url: root.couponInter.coupon_saveSendCoupon,
            cache: false,  //禁用缓存
            type: "POST",
            dataType: 'json',
            contentType: "application/json",
            data: JSON.stringify({
                "couponSend": {
                    "sendCustType": custType,
                    "sendCouponName": $('#sendCouponName').val(),
                    "sendCouponDept": $('#sendCouponDept').html(),
                    "sendCouponUser": $('#sendCouponUser').html(),
                    "sendCouponType": sendCouponType,
                    "sendReasonDutyDept": $('#sendReasonDutyDept').val(),
                    "sendCouponReason": $('#sendCouponReason').val(),
                    // "auditStatus":"",
                    "description": $('#description').val(),
                    "token": tokenVal,
                    "auditPerson": '',
                    "customerType": customerTypess,
                    "sendCondition": sendCondition,
                    "orderAmount": $('#orderAmount').val(),
                    "applWarehouse": wareHouse,
                    "applPaidType": payType,
                    "startTime": $('#logmin').val(),
                    "endTime": $('#logmax').val(),
                    "priceType":$("input[name=priceType]:checked").val()
                },
                "sendCustomers": addList,
                "sendTopics": sendTopics
            }),
            success: function (data) {
                console.log(data)
                if (data.errorCode == 0) {
                    //影藏等待样式
                    $("#beijing").css("display", "none");
                    $("#myLoading").css("display", "none");
                    $.Huimodalalert('创建成功！', 2000);
                    setTimeout(function () {
                        location.reload();
                    }, 1100);
                }
                else {
                    //影藏等待样式
                    $("#beijing").css("display", "none");
                    $("#myLoading").css("display", "none");
                    $("#bottm").attr("disabled", false);
                    $.Huimodalalert(data.msg, 2000);
                    sendCustomers = [];
                    sendTopics = [];
                }
            },
            error: function () {
                //影藏等待样式
                $("#beijing").css("display", "none");
                $("#myLoading").css("display", "none");
                $("#bottm").attr("disabled", false);
                $.Huimodalalert('修改失败！', 2000);
            }
        });
    }
})

//发券原因二级联动
var oldVal = '';

function sendDeptChange(Val) {
    if (oldVal != Val) {
        $('#sendCouponReason').val('')
    }
    oldVal = Val;
    console.log(Val);
    var option = document.getElementsByClassName('options');
    console.log(option);
    switch (parseInt(Val)) {
        case 1:
            for (var i = 0; i < option.length; i++) {
                if (option[i].value == 11 || option[i].value == 12) {
                    console.log(option[i]);
                    option[i].classList.remove('hide');
                }
                else {
                    option[i].classList.add('hide');
                }
            }
            break;
        case 2:
            for (var i = 0; i < option.length; i++) {
                if (option[i].value > 20 && option[i].value < 28) {
                    console.log(option[i]);
                    option[i].classList.remove('hide');
                }
                else {
                    option[i].classList.add('hide');
                }
            }
            break;
        case 3:
            for (var i = 0; i < option.length; i++) {
                if (option[i].value > 30 && option[i].value < 35) {
                    console.log(option[i]);
                    option[i].classList.remove('hide');
                }
                else {
                    option[i].classList.add('hide');
                }
            }
            break;
        case 4:
            for (var i = 0; i < option.length; i++) {
                if (option[i].value > 40 && option[i].value < 49) {
                    console.log(option[i]);
                    option[i].classList.remove('hide');
                }
                else {
                    option[i].classList.add('hide');
                }
            }
            break;
        case 5:
            for (var i = 0; i < option.length; i++) {
                if (option[i].value > 50 && option[i].value < 59) {
                    console.log(option[i]);
                    option[i].classList.remove('hide');
                }
                else {
                    option[i].classList.add('hide');
                }
            }
            break;
        case 6:
            for (var i = 0; i < option.length; i++) {
                if (option[i].value > 60 && option[i].value < 69) {
                    console.log(option[i]);
                    option[i].classList.remove('hide');
                }
                else {
                    option[i].classList.add('hide');
                }
            }
            break;
        case 7:
            for (var i = 0; i < option.length; i++) {
                if (option[i].value > 70 && option[i].value < 79) {
                    console.log(option[i]);
                    option[i].classList.remove('hide');
                }
                else {
                    option[i].classList.add('hide');
                }
            }
            break;
    }
}


Array.prototype.distinct = function () {
    var arr = this,
        result = [],
        len = arr.length;
    arr.forEach(function (v, i, arr) {  //这里利用map，filter方法也可以实现
        var bool = arr.indexOf(v, i + 1);  //从传入参数的下一个索引值开始寻找是否存在重复
        if (bool === -1) {
            result.push(v);
        }
    })
    return result;
};

function shuanxin() {
    console.log(22222);
    var interv = setInterval(function () {
        console.log(1111)
        $("#topic-2").load(location.href + " #topic-2");
    }, 2000);
    clearInterval(interv);
}

Array.prototype.unique = function (array) {     // 对象去重方法
    var allArr = [];    //建立新的临时数组
    for (var i = 0; i < array.length; i++) {
        var flag = true;
        for (var j = 0; j < allArr.length; j++) {
            if (array[i].cityId == allArr[j].cityId) {
                flag = false;
            }
            ;
        }
        ;
        if (flag) {
            allArr.push(array[i]);
        }
        ;
    }
    ;
    return allArr;
}